package com.softer.wxzj.service.impl;

import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.util.OperUtil;
import com.softer.wxzj.common.util.ShiroUserUtil;
import com.softer.wxzj.entity.BaseRegionInfo;
import com.softer.wxzj.entity.ResourceTree;
import com.softer.wxzj.entity.SysLoginInfo;
import com.softer.wxzj.entity.SysResource;
import com.softer.wxzj.mapper.HomeMapper;
import com.softer.wxzj.mapper.OrgBuildAuditMapper;
import com.softer.wxzj.service.HomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * HomeServiceImpl class
 *
 * @author zcz
 * @date 2019/1/16
 */
@Service
public class HomeServiceImpl implements HomeService {

    @Autowired
    private HomeMapper homeMapper;
    @Autowired
    private OrgBuildAuditMapper orgBuildAuditMapper;
    @Autowired
    private OperUtil zoneCodeUtil;
    private final String ORGANIZATION_ADD = "organization_add";
    private final String ORGANIZATION_MODIFY = "organization_modify";
    private final String COMMITTEE_REGISTER = "committee_register";
    private final String COMMITTEE_UPDATE = "committee_update";
    private final String REGION_INFO_ADD = "region_info_add";
    private final String BASE_BUILD_INFO_REGISTER = "base_build_info_register";
    private final String REGION_INFO_MODIFY = "region_info_modify";
    private final String BASE_CELL_INFO_UPDATE = "base_cell_info_update";
    private final String BASE_HOUSE_INFO_STRUCTURE = "base_house_info_structure";
    private final String BASE_BUILD_INFO_UPDATE = "base_build_info_update";
    private final String BASE_HOUSE_INFO_UPDATE = "base_house_info_update";
    private final String BASE_OWNER_INFO_UPDATE = "base_owner_info_update";
    private final String SPLIT_MERGE = "split_merge";
    private final String HOUSE_MODIFY = "house_modify";
    private final String DEPOSIT = "deposit";
    private final String PROJECT_REQ = "project_req";
    private final String INTRANET_EMERGENCY = "intranet_emergency";
    private final String NEIGHBORHOOD_COMMITTEE_EMERGENCY = "neighborhood_committee_emergency";
    private final String INDUSTRY_COMMITTEE_EMERGENCY = "industry_committee_emergency";
    private final String PAY_REQ = "pay_req";
    private final String PAY_REVOCATION = "pay_revocation";
    private final String PROJECT_REVOCATION = "project_revocation";
    private final String TRANS_REQ = "trans_req";
    private final String REF_REQ = "ref_req";
    private final String CLOSE_ACCOUNT = "close_account";
    private final String DEPOSIT_DEVELOP = "deposit_develop";
    private final String DEPOSIT_CONTINUATION = "deposit_continuation";
    private final String REGION_BINDING = "region_binding";

    @Override
    public List<SysResource> getMenu(String userName) {
        //根据当前用户类型查询不同用户表对应的菜单
        return homeMapper.getSysOperMenu(userName);
    }

    private String getConfigIdByOperNo() {
        return homeMapper.getConfigIdByOperNo(ShiroUserUtil.getUserName());
    }


    @Override
    public List<ResourceTree> getResourceTree() {
        List<ResourceTree> list = homeMapper.getResourceTree(ShiroUserUtil.getUserName());
        List<ResourceTree> oneList = list.stream().filter(p -> "0".equals(p.getParentId())).collect(Collectors.toList());
        for (int i = 0; i < oneList.size(); i++) {
            String id = oneList.get(i).getId();
            List<ResourceTree> twoList = list.stream().filter(p -> p.getParentId().equals(id)).collect(Collectors.toList());
            for (int m = 0; m < twoList.size(); m++) {
                String sid = twoList.get(m).getId();
                List<ResourceTree> threeList = list.stream().filter(p -> p.getParentId().equals(sid)).collect(Collectors.toList());

                List<ResourceTree> threeList1 = threeList.stream().filter(p -> "1".equals(p.getType())).collect(Collectors.toList());
                for (int n = 0; n < threeList1.size(); n++) {
                    String tid = threeList1.get(n).getId();
                    List<ResourceTree> fourBtnList = list.stream().filter(p -> p.getParentId().equals(tid)).collect(Collectors.toList());
                    for (int t = 0; t < fourBtnList.size(); t++) {
                        String bid = fourBtnList.get(t).getId();
                        List<ResourceTree> fiveBtnList = list.stream().filter(p -> p.getParentId().equals(bid)).collect(Collectors.toList());
                        fourBtnList.get(t).setChildren(fiveBtnList);
                    }
                    threeList1.get(n).setChildren(fourBtnList);
                }
                List<ResourceTree> threeBtnList = threeList.stream().filter(p -> "2".equals(p.getType())).collect(Collectors.toList());
                for (int t = 0; t < threeBtnList.size(); t++) {
                    String bid = threeBtnList.get(t).getId().toString();
                    List<ResourceTree> fourBtnList = list.stream().filter(p -> p.getParentId().equals(bid)).collect(Collectors.toList());
                    threeBtnList.get(t).setChildren(fourBtnList);
                }
                threeList1.addAll(threeBtnList);
                twoList.get(m).setChildren(threeList1);
            }
            oneList.get(i).setChildren(twoList);
        }
        return oneList;
    }

    @Override
    public List<Map<String, String>> getHomeTotal() {
        List<Map<String, String>> list = new ArrayList<>(5);
        list.add(putOrganizationTotalMap(NumStrEnum.ONE.getNum()));
        list.add(getExpProjectTotalMap(NumStrEnum.FOUR.getNum()));
        list.add(getRefReqCount(NumStrEnum.FIVE.getNum()));
        list.add(queryTheCommunityFile(NumStrEnum.TWO.getNum()));
        list.add(depositAndMaintenance(NumStrEnum.THREE.getNum()));
        list.add(regionBinding(NumStrEnum.SIX.getNum()));
        return list;
    }

    /**
     * 获取上次登录记录
     *
     * @return 上次登录记录
     */
    @Override
    public SysLoginInfo getLoginInfo(String operNo) {
        List<SysLoginInfo> list = homeMapper.getLoginInfo(operNo);
        if (list != null && list.size() > 1) {
            return list.get(1);
        }
        return new SysLoginInfo();
    }

    /**
     * 主页登陆人管辖范围
     *
     * @param operNo 登陆人帐号
     * @return
     */
    @Override
    public List<BaseRegionInfo> getAllRegionByOperNo(String operNo) {
        List<BaseRegionInfo> regionInfos = orgBuildAuditMapper.getAllRegionByOperNo(operNo);
        return regionInfos;
    }

    @Override
    public List<Map<String, String>> getHomeDetailTotal(String code) {
        List<Map<String, String>> list = new ArrayList<>();
        switch (code) {
            case "1":
                list = putOrganizationTotalMapDetail();
                break;
            case "2":
                list = queryTheCommunityFileDetail();
                break;
            case "3":
                list = depositAndMaintenanceDetil();
                break;
            case "4":
                list = getExpProjectTotalMapDetail();
                break;
            case "5":
                list = getRefReqCountDetail();
                break;
            case "6":
                list = getRegionBinding();
                break;
        }
        return list;
    }

    private List<Map<String, String>> putOrganizationTotalMapDetail() {
        List<Map<String, String>> baseOrganization = homeMapper.getBaseOrganization(zoneCodeUtil.getZoneCode(), NumStrEnum.ONE.getNum(), getConfigIdByOperNo());
        List<Map<String, String>> baseOwnerCommittee = homeMapper.getBaseOwnerCommittee(zoneCodeUtil.getZoneCode(), NumStrEnum.ONE.getNum(), getConfigIdByOperNo());
        baseOrganization.addAll(baseOwnerCommittee);
        for (Map<String, String> m : baseOrganization) {
            Map<String, String> map = getDetail(m.get("orgTypeCode"), m.get("flowType"));
            m.put("url", map.get("url"));
            m.put("name", map.get("name"));
            m.put("id", map.get("id"));
        }
        return baseOrganization;
    }


    private Map<String, String> putOrganizationTotalMap(String code) {
        HashMap<String, String> map = new HashMap<>(8);
        int countOrganization = 0;
        int countOwnerCommittee = 0;
        List<Map<String, String>> baseOrganization = homeMapper.getBaseOrganization(zoneCodeUtil.getZoneCode(), null, getConfigIdByOperNo());
        List<Map<String, String>> baseOwnerCommittee = homeMapper.getBaseOwnerCommittee(zoneCodeUtil.getZoneCode(), null, getConfigIdByOperNo());
        countOrganization = null == baseOrganization.get(0).get("count") ? countOrganization : Integer.parseInt(baseOrganization.get(0).get("count"));
        countOwnerCommittee = null == baseOwnerCommittee.get(0).get("count") ? countOwnerCommittee : Integer.parseInt(baseOwnerCommittee.get(0).get("count"));
        map.put("count", String.valueOf(countOrganization + countOwnerCommittee));
        map.put("code", code);
        map.put("id", map.get("id"));
        return map;
    }

    private List<Map<String, String>> getRefReqCountDetail() {
        List<Map<String, String>> refReqCount = homeMapper.getRefReqCount(zoneCodeUtil.getZoneCode(), NumStrEnum.ONE.getNum(), getConfigIdByOperNo());
        List<Map<String, String>> tranReq = homeMapper.getTransReq(zoneCodeUtil.getZoneCode(), NumStrEnum.ONE.getNum(), getConfigIdByOperNo());
        refReqCount.addAll(tranReq);
        setParam(refReqCount);
        return refReqCount;
    }

    /**
     * 区域管理
     *
     * @return
     */
    private List<Map<String, String>> getRegionBinding() {
        List<Map<String, String>> regionBinding = homeMapper.regionBinding(zoneCodeUtil.getZoneCode(), NumStrEnum.ONE.getNum(), getConfigIdByOperNo());
        setParam(regionBinding);
        return regionBinding;
    }

    private Map<String, String> getRefReqCount(String code) {
        int tranReqs = 0;
        int expProjectCounts = 0;
        HashMap<String, String> map = new HashMap<>();
        List<Map<String, String>> expProjectCount = homeMapper.getRefReqCount(zoneCodeUtil.getZoneCode(), null, getConfigIdByOperNo());
        List<Map<String, String>> tranReq = homeMapper.getTransReq(zoneCodeUtil.getZoneCode(), null, getConfigIdByOperNo());
        tranReqs = (null == tranReq.get(0).get("count") ? tranReqs : Integer.parseInt(tranReq.get(0).get("count")));
        expProjectCounts = null == expProjectCount.get(0).get("count") ? expProjectCounts : Integer.parseInt(expProjectCount.get(0).get("count"));
        map.put("count", String.valueOf(expProjectCounts + tranReqs));
        map.put("code", code);
        map.put("id", map.get("id"));
        return map;
    }

    private List<Map<String, String>> getExpProjectTotalMapDetail() {
        List<Map<String, String>> expProjectCount = homeMapper.getExpProjectCount(zoneCodeUtil.getZoneCode(), NumStrEnum.ONE.getNum(), getConfigIdByOperNo());
        List<Map<String, String>> expProjectPayCount = homeMapper.getExpProjectPayCount(zoneCodeUtil.getZoneCode(), NumStrEnum.ONE.getNum(), getConfigIdByOperNo());
        List<Map<String, String>> expProjectDelCount = homeMapper.getExpProjectDelCount(zoneCodeUtil.getZoneCode(), NumStrEnum.ONE.getNum(), getConfigIdByOperNo());
        List<Map<String, String>> expProjectPayDelCount = homeMapper.getExpProjectPayDelCount(zoneCodeUtil.getZoneCode(), NumStrEnum.ONE.getNum(), getConfigIdByOperNo());
        expProjectCount.addAll(expProjectDelCount);
        expProjectCount.addAll(expProjectPayDelCount);
        expProjectCount.addAll(expProjectPayCount);
        setParam(expProjectCount);
        return expProjectCount;
    }

    private void setParam(List<Map<String, String>> expProjectCount) {
        for (Map<String, String> m : expProjectCount) {
            Map<String, String> map = getDetail(null, m.get("flowType"));
            m.put("url", map.get("url"));
            m.put("name", map.get("name"));
            m.put("id", map.get("id"));
        }
    }

    private Map<String, String> getExpProjectTotalMap(String code) {
        HashMap<String, String> map = new HashMap<>();
        int expProjectCountNum = 0;
        int expProjectPayCountNum = 0;
        int expProjectDelCountNum = 0;
        int expProjectPayDelCountNum = 0;
        List<Map<String, String>> expProjectCount = homeMapper.getExpProjectCount(zoneCodeUtil.getZoneCode(), null, getConfigIdByOperNo());
        List<Map<String, String>> expProjectPayCount = homeMapper.getExpProjectPayCount(zoneCodeUtil.getZoneCode(), null, getConfigIdByOperNo());
        List<Map<String, String>> expProjectDelCount = homeMapper.getExpProjectDelCount(zoneCodeUtil.getZoneCode(), null, getConfigIdByOperNo());
        List<Map<String, String>> expProjectPayDelCount = homeMapper.getExpProjectPayDelCount(zoneCodeUtil.getZoneCode(), null, getConfigIdByOperNo());
        expProjectDelCountNum = (null == expProjectDelCount.get(0).get("count") ? expProjectDelCountNum : Integer.parseInt(expProjectDelCount.get(0).get("count")));
        expProjectPayDelCountNum = null == expProjectPayDelCount.get(0).get("count") ? expProjectPayDelCountNum : Integer.parseInt(expProjectPayDelCount.get(0).get("count"));
        expProjectCountNum = (null == expProjectCount.get(0).get("count") ? expProjectCountNum : Integer.parseInt(expProjectCount.get(0).get("count")));
        expProjectPayCountNum = null == expProjectPayCount.get(0).get("count") ? expProjectPayCountNum : Integer.parseInt(expProjectPayCount.get(0).get("count"));
        map.put("count", String.valueOf(expProjectCountNum + expProjectPayCountNum + expProjectPayDelCountNum + expProjectDelCountNum));
        map.put("code", code);
        map.put("id", map.get("id"));
        return map;
    }

    private List<Map<String, String>> queryTheCommunityFileDetail() {
        List<Map<String, String>> list = homeMapper.queryTheCommunityFile(zoneCodeUtil.getZoneCode(), NumStrEnum.ONE.getNum(), getConfigIdByOperNo());
        setParam(list);
        return list;
    }

    private Map<String, String> queryTheCommunityFile(String code) {
        HashMap<String, String> map = new HashMap<>();
        List<Map<String, String>> list = homeMapper.queryTheCommunityFile(zoneCodeUtil.getZoneCode(), null, getConfigIdByOperNo());
        map.put("count", list.get(0).get("count"));
        map.put("code", code);
        map.put("id", map.get("id"));
        return map;
    }

    private List<Map<String, String>> depositAndMaintenanceDetil() {
        List<Map<String, String>> list = homeMapper.depositAndMaintenance(zoneCodeUtil.getZoneCode(), NumStrEnum.ONE.getNum(), getConfigIdByOperNo());
        List<Map<String, String>> expProjectCount = homeMapper.depositAndDepMaintenance(zoneCodeUtil.getZoneCode(), NumStrEnum.ONE.getNum(), getConfigIdByOperNo());
        List<Map<String, String>> depositAndConMaintenance = homeMapper.depositAndConMaintenance(zoneCodeUtil.getZoneCode(), NumStrEnum.ONE.getNum(), getConfigIdByOperNo());
        list.addAll(expProjectCount);
        list.addAll(depositAndConMaintenance);
        setParam(list);
        return list;
    }

    private Map<String, String> regionBinding(String code) {
        HashMap<String, String> map = new HashMap<>(8);
        int regionBindingNum = 0;
        List<Map<String, String>> regionBindingCount = homeMapper.regionBinding(zoneCodeUtil.getZoneCode(), null, getConfigIdByOperNo());
        regionBindingNum = (null == regionBindingCount.get(0).get("count") ? regionBindingNum : Integer.parseInt(regionBindingCount.get(0).get("count")));
        map.put("count", String.valueOf(regionBindingNum));
        map.put("code", code);
        map.put("id", map.get("id"));
        return map;
    }

    private Map<String, String> depositAndMaintenance(String code) {
        HashMap<String, String> map = new HashMap<>(8);
        int depositCountNum = 0;
        int depositDepCountNum = 0;
        int depositConCountNum = 0;
        List<Map<String, String>> refReqCount = homeMapper.depositAndMaintenance(zoneCodeUtil.getZoneCode(), null, getConfigIdByOperNo());
        List<Map<String, String>> expProjectCount = homeMapper.depositAndDepMaintenance(zoneCodeUtil.getZoneCode(), null, getConfigIdByOperNo());
        List<Map<String, String>> depositAndConMaintenance = homeMapper.depositAndConMaintenance(zoneCodeUtil.getZoneCode(), null, getConfigIdByOperNo());
        depositCountNum = (null == refReqCount.get(0).get("count") ? depositCountNum : Integer.parseInt(refReqCount.get(0).get("count")));
        depositDepCountNum = null == expProjectCount.get(0).get("count") ? depositDepCountNum : Integer.parseInt(expProjectCount.get(0).get("count"));
        depositConCountNum = null == depositAndConMaintenance.get(0).get("count") ? depositConCountNum : Integer.parseInt(depositAndConMaintenance.get(0).get("count"));
        map.put("count", String.valueOf(depositCountNum + depositDepCountNum + depositConCountNum));
        map.put("code", code);
        map.put("id", map.get("id"));
        return map;
    }

    private Map<String, String> getDetail(String code, String flowType) {
        HashMap<String, String> map = new HashMap<>(8);
        String url = null;
        String name = null;
        String id = null;
        //01开发企业，02物业企业，03施工企业，04监理企业，08审计企业
        if (ORGANIZATION_ADD.equals(flowType) && "01".equals(code)) {
            url = "/home/approvedevlist";
            name = "开发企业备案审核";
            id = "236";
        } else if (ORGANIZATION_ADD.equals(flowType) && "02".equals(code)) {
            url = "/home/approveproperlylist";
            name = "物业企业备案审核";
            id = "238";
        } else if (ORGANIZATION_ADD.equals(flowType) && "03".equals(code)) {
            url = "/home/approvebuildlist";
            name = "施工企业备案审核";
            id = "240";
        } else if (ORGANIZATION_ADD.equals(flowType) && "04".equals(code)) {
            url = "/home/approvesupervisorlist";
            name = "监理企业备案审核";
            id = "242";
        } else if (ORGANIZATION_ADD.equals(flowType) && "08".equals(code)) {
            url = "/home/approveauditlist";
            name = "审计企业备案审核";
            id = "244";
        } else if (ORGANIZATION_MODIFY.equals(flowType) && "01".equals(code)) {
            url = "/home/changeapprovedevlist";
            name = "开发企业变更审核";
            id = "281";
        } else if (ORGANIZATION_MODIFY.equals(flowType) && "02".equals(code)) {
            url = "/home/changeapproveproperlylist";
            name = "物业企业变更审核";
            id = "68";
        } else if (ORGANIZATION_MODIFY.equals(flowType) && "03".equals(code)) {
            url = "/home/changeapprovebuildlist";
            name = "施工企业变更审核";
            id = "75";
        } else if (ORGANIZATION_MODIFY.equals(flowType) && "04".equals(code)) {
            url = "/home/changeapprovesupervisorlist";
            name = "监理企业变更审核";
            id = "82";
        } else if (ORGANIZATION_MODIFY.equals(flowType) && "08".equals(code)) {
            url = "/home/changeapproveauditlist";
            name = "审计企业变更审核";
            id = "89";
        } else if (COMMITTEE_REGISTER.equals(flowType) && "05".equals(code)) {
            //05也维  06居委会
            url = "/home/approveownerlist";
            name = "业委会备案审核";
            id = "246";
        } else if (COMMITTEE_REGISTER.equals(flowType) && "06".equals(code)) {
            url = "/home/approvedwelllist";
            name = "居委会备案审核";
            id = "248";
        } else if (COMMITTEE_UPDATE.equals(flowType) && "05".equals(code)) {
            url = "/home/changeapproveownerlist";
            name = "业委会变更审核";
            id = "52";
        } else if (COMMITTEE_UPDATE.equals(flowType) && "06".equals(code)) {
            url = "/home/changeapprovedwelllist";
            name = "居委会变更审核";
            id = "59";
        } else if (REGION_INFO_ADD.equals(flowType)) {
            url = "/home/communitybaseinfoapprove";
            name = "小区信息审核";
            id = "113";
        } else if (BASE_BUILD_INFO_REGISTER.equals(flowType)) {
            url = "/home/floorbaseinfoapprove";
            name = "自然幢信息审核";
            id = "114";
        } else if (REGION_INFO_MODIFY.equals(flowType)) {
            url = "/home/communitychangeapprovelist";
            name = "小区变更审核";
            id = "128";
        } else if (BASE_CELL_INFO_UPDATE.equals(flowType)) {
            url = "/home/unitChangeApproveList";
            name = "单元结构变更审核";
            id = "672";
        } else if (BASE_HOUSE_INFO_STRUCTURE.equals(flowType)) {
            url = "/home/houseStructureChangeApproveList";
            name = "房屋结构变更审核";
            id = "677";
        } else if (BASE_BUILD_INFO_UPDATE.equals(flowType)) {
            url = "/home/floorchangeapprovelist";
            name = "自然幢变更审核";
            id = "129";
        } else if (BASE_HOUSE_INFO_UPDATE.equals(flowType)) {
            url = "/home/housechangeapprovelist";
            name = "房屋变更审核";
            id = "137";
        } else if (BASE_OWNER_INFO_UPDATE.equals(flowType)) {
            url = "/home/ownerchangeapprovelist";
            name = "业主变更审核";
            id = "130";
        } else if (SPLIT_MERGE.equals(flowType)) {
            url = "/home/housesplitapprovelist";
            name = "房屋拆分/合并审核";
            id = "136";
        } else if (HOUSE_MODIFY.equals(flowType)) {
            url = "/home/houseownerchangelist";
            name = "房屋调换审核";
            id = "131";
        } else if (DEPOSIT.equals(flowType)) {
            url = "/home/depositCheckList";
            name = "资金交存审核";
            id = "404";
        } else if (PROJECT_REQ.equals(flowType)) {
            url = "/home/projectApproveList";
            name = "项目审批";
            id = "516";
        } else if (INDUSTRY_COMMITTEE_EMERGENCY.equals(flowType)) {
            url = "/home/projectApproveList";
            name = "业委会应急审批";
            id = "516";
        } else if (INTRANET_EMERGENCY.equals(flowType)) {
            url = "/home/projectApproveList";
            name = "内网应急审批";
            id = "516";
        } else if (NEIGHBORHOOD_COMMITTEE_EMERGENCY.equals(flowType)) {
            url = "/home/projectApproveList";
            name = "居委会应急审批";
            id = "516";
        } else if (PAY_REQ.equals(flowType)) {
            url = "/home/grantReview";
            name = "拨款审核";
            id = "508";
        } else if (PAY_REVOCATION.equals(flowType)) {
            url = "/home/appropriationWithdrawalApprove";
            name = "拨款申请撤销";
            id = "502";
        } else if (PROJECT_REVOCATION.equals(flowType)) {
            url = "/home/projectWithdrawalApprove";
            name = "维修项目撤回";
            id = "501";
        } else if (TRANS_REQ.equals(flowType)) {
            url = "/home/housRrefundapprovelist";
            name = "过户审核";
            id = "413";
        } else if (REF_REQ.equals(flowType)) {
            url = "/home/refundApproveList";
            name = "退款审批";
            id = "464";
        } else if (CLOSE_ACCOUNT.equals(flowType)) {
            url = "/home/refundApproveList";
            name = "销户审批";
            id = "464";
        } else if (DEPOSIT_DEVELOP.equals(flowType)) {
            url = "/home/CapitalReplenishmentApproveList";
            name = "资金补齐审批";
            id = "751";
        } else if (DEPOSIT_CONTINUATION.equals(flowType)) {
            url = "/home/FundRenewalManagement";
            name = "资金续交审批";
            id = "768";
        } else if (REGION_BINDING.equals(flowType)) {
            url = "/home/Regionalism";
            name = "区域划分审批";
            id = "744";
        }
        map.put("url", url);
        map.put("name", name);
        map.put("id", id);
        return map;
    }

}
